<?php
class Media
{
	private static $_instance = null;
	private $_db = null;
	
	private function __construct()
	{
		$this->_db = Yii::app()->db;
		$this->_db->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
	}
	
	public static function getInstance() 
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
	
	public function getList(array $args = array(), $intPage = 1, $intLimit = MIN_ROWS_PER_PAGE)
	{
		try{
			$defaults = array(
				'site_id' => SITE,
				'sort' => null,
				'keyword' => null,
				'file_type' => null,
				'label' => null
			);
			$args = array_merge($defaults, $args);
			foreach($args as &$r){
				if($r == '') $r = null;	
			}

			$intStart = ($intPage-1)*$intLimit;
			
			$strSQL = " 	
						SELECT SQL_CALC_FOUND_ROWS * 
						FROM tbl_cms_media
						WHERE site_id = :site 
							  AND media_group_label <=> IFNULL(:label, media_group_label) 
							  AND FIND_IN_SET(media_file_extension, IFNULL(:file_type, media_file_extension))
							  AND media_title LIKE IFNULL(:keyword, media_title)
						ORDER BY media_id DESC
						LIMIT :intStart, :intLimit
					  ";
			$cmd = $this->_db->createCommand($strSQL);	
			$cmd->bindParam(":site",$args['site_id'],PDO::PARAM_INT);
			$cmd->bindParam(":label",$args['label'],PDO::PARAM_INT);
			$cmd->bindParam(":file_type",$args['file_type'],PDO::PARAM_INT);
			$cmd->bindParam(":keyword",$args['keyword'],PDO::PARAM_INT);
			$cmd->bindParam(":intStart",$intStart,PDO::PARAM_INT);
			$cmd->bindParam(":intLimit",$intLimit,PDO::PARAM_INT);
			$arrResults = $cmd->queryAll();
			if(!empty($arrResults)){
				$arrResults[0]['total_rows'] = $this->_db->createCommand('SELECT FOUND_ROWS();')->queryScalar();
			}
			return $arrResults;
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function insert(array $args){
		try{
			$defaults = array(
				'site_id' => SITE,
				'media_title' => null,
				'media_description' => null,
				'media_file' => null,
				'media_file_size' => null,
				'media_file_extension' => null,
				'media_alt' => null,
				'media_created_date' => date('Y-m-d H:i:s'),
				'media_status' => 1,
			);
			$args = array_merge($defaults, $args);
			
			$cmd = $this->_db->createCommand();
			$cmd->insert('tbl_cms_media',$args);
			return Yii::app()->db->getLastInsertId();
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
}